package com.heima.wemedia.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.file.service.FileStorageService;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;

    @Resource
    private WmNewsService wmNewsService;

    /**
     * 图片上传
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        /**
         * 1.multipartFile == null：检查 multipartFile 是否为 null，也就是说，是否没有上传文件。
         * 如果 multipartFile 为 null，表示没有接收到任何文件。
         * 2.multipartFile.getSize() == 0：检查文件的大小是否为 0 字节。如果文件大小为 0，通常表示用户上传了一个空文件。
         */
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.上传图片到minIO中
        String originalFilename = multipartFile.getOriginalFilename();//获取原始文件名
        String postfix = StrUtil.subAfter(originalFilename, ".", true);//获取文件后缀名
        String fileName = StrUtil.format("{}.{}", IdUtil.simpleUUID(), postfix);//生成唯一文件名
        String fileId;//定义文件ID
        try {
            fileId = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
            log.info("上传图片到Minio中，fileId={}", fileId);
        } catch (IOException e) {
            log.error("WmMaterialServiceImpl 上传图片到Minio失败");
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "上传图片到Minio失败");
        }


        //3.保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public PageResponseResult<List<WmMaterial>> findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();
        //2.分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.lambdaQuery();
        //是否收藏

        lambdaQueryWrapper.eq(ObjectUtil.equal(dto.getIsCollection(), 1), WmMaterial::getIsCollection, dto.getIsCollection());

        //按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());

        //按照时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //查询数据
        super.page(page, lambdaQueryWrapper);

        //3.结果返回
        return PageResponseResult.<List<WmMaterial>>builder()
                .currentPage(dto.getPage())
                .size(dto.getSize())
                .total(Convert.toInt(page.getTotal()))
                .data(page.getRecords())
                .build();
    }

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult<AppHttpCodeEnum> delPicture(Long id) {
        //1.检查参数是否失效
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        // 如果查询结果为 null，返回 ID 不存在的错误信息
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        try {
            this.removeById(id);
            // 如果查询结果不为 null，返回成功信息
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("WmMaterialServiceImpl 删除失败");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "删除失败");
        }


    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult<AppHttpCodeEnum> collect(Long id) {

        try {
            this.lambdaUpdate()
                    .eq(WmMaterial::getId, id)
                    .set(WmMaterial::getIsCollection, (short) 1)
                    .update();

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("WmMaterialServiceImpl 参数失效");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult<AppHttpCodeEnum> cancelCollect(Long id) {
        try {
            this.lambdaUpdate()
                    .eq(WmMaterial::getId, id)
                    .set(WmMaterial::getIsCollection, (short) 0).update();

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Long id) {
        try {
            LambdaQueryChainWrapper<WmMaterial> eq = lambdaQuery().eq(WmMaterial::getId, id);
            return ResponseResult.okResult(eq.one());
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

    }

    /**
     * 删除新闻
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Long id) {
        //1.检查参数是否失效
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章ID不能为空");
        }
        WmMaterial wmMaterial = this.getById(id);
        // 如果查询结果为 null，返回 ID 不存在的错误信息
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        try {
            this.removeById(id);
            // 如果查询结果不为 null，返回成功信息
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章已经发布，不能删除");
        }
    }

    /**
     * 上架或者下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章ID不能为空");
        }
        // 如果查询结果为 null，返回 ID 不存在的错误信息
        if (dto.getId() == null) {


            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        try {
            wmNewsService.lambdaUpdate()
                    .eq(WmNews::getId, dto.getId())
                    .set(WmNews::getEnable, dto.getEnable())
                    .update();
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章不是发布状态，不能上下架");
        }

    }


}
